//
//  HistorySearchViewController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/18.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "HistorySearchViewController.h"
#import "CJCalendarViewController.h"
#import "EventBaseCell.h"
#import "MJRefresh.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "AppConstants.h"
#import "UIView+Addition.h"
#import "InprogressController.h"
#import "UnStartEventController.h"
#import "SVProgressHUD.h"
#import "HistoryInidentDetailController.h"
#import "HistoryConstructDetailController.h"
#import "CurrentContructDetailViewController.h"
#import "CurrentIncidentDetailViewController.h"
#import "AppLocalManager.h"

@interface HistorySearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,CalendarViewControllerDelegate, UIPopoverPresentationControllerDelegate>
@property (strong, nonatomic) UISearchBar *searchBar;
@property (nonatomic,strong)UIView *meesageV;
@property (nonatomic, strong)UIButton *calendarBtn;
@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, strong) UIButton *constructEventBtn; //施工事件
@property (nonatomic, strong) UIButton *incidentEventBtn;  //事故事件
@property (nonatomic, strong) UIView   *containerView;
@property (nonatomic, strong) UIView   *verLineView;

@property (assign, nonatomic) NSInteger currentPageIndex;
@property (assign, nonatomic) NSInteger currentSearchWay;
@property (copy  , nonatomic) NSString *searchContentStr;
@property (nonatomic, strong) NSString *EventType;
@property (strong, nonatomic) NSMutableArray *searchDataArray;
@property (nonatomic, assign) NSInteger howToSearch; // 1: searchBar 2: 日历 3施工按钮 4 事故按钮

@end

static NSString *cellID = @"searchCell";
@implementation HistorySearchViewController

#pragma   ---------历史事件  搜索功能


- (void)viewDidLoad {
    [super viewDidLoad];
    [self configDefault];
    [self configNavitationBar];
    [self configEvenTypeView];
    [self configTableView];
    [self configCalendarBtn];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    //self.tableView.backgroundColor = [UIColor blueColor];
}
- (void) configDefault {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
    NSInteger inter = _titleType;
    NSInteger eIn    = inter + 1;
    _EventType       = [NSString stringWithFormat:@"%ld", (long)eIn];
    self.searchDataArray = [[NSMutableArray alloc] init];
    
}
//设置标题
- (void)configNavitationBar {
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"请输入搜索的关键字";
    self.navigationItem.titleView = _searchBar;
    _searchBar.delegate = self;
    [_searchBar becomeFirstResponder];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"left_narrow"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
}
- (void) popBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) configEvenTypeView {
    _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, 44)];
    _containerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_containerView];
    
    _verLineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.width / 2, 2, 1, 40)];
    _verLineView.backgroundColor = [UIColor lightGrayColor];
    [_containerView addSubview:_verLineView];
    
    _constructEventBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, (self.view.width / 2), 44)];
    [_constructEventBtn setTitle:@"施工事件" forState:UIControlStateNormal];
    [_constructEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    _constructEventBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_constructEventBtn addTarget:self action:@selector(constructEventBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_containerView addSubview: _constructEventBtn];
    
    _incidentEventBtn = [[UIButton alloc] initWithFrame:CGRectMake((self.view.width) / 2, 0, (self.view.width / 2), 44)];
    [_incidentEventBtn setTitle:@"事故事件" forState:UIControlStateNormal];
    _incidentEventBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_incidentEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_incidentEventBtn addTarget:self action:@selector(incidentEventBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_containerView addSubview:_incidentEventBtn];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    if([searchBar.text length] > 0) {  // 有输入
        [_searchBar resignFirstResponder];
        self.currentSearchWay = 1;
        self.howToSearch      = 1;
        NSString *contentStr  = searchBar.text;
        self.currentPageIndex = 1;
        self.searchContentStr = contentStr;
        [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:1 searchContentString:contentStr];
    }else { // 无输入
        return;
    }
}
#pragma mark - 按钮点击
#pragma mark - 搜索施工事件
-(NSString *)DataValueStr:(NSString *)lastEventUID pageIndex:(NSString *)pageIndex pageSize:(NSString *)pageSize incidentType:(NSString *)incidentType {
    NSString *valueStr =[NSString stringWithFormat:                                            @"[{\"Key\":\"LastEventUID\",\"Value\":\"%@\"},                               {\"Key\":\"PageIndex\",\"Value\":\"%@\"},                                                  {\"Key\":\"PageSize\",\"Value\":\"%@\"},                                               {\"Key\":\"IncidentType\",\"Value\":\"%@\"}]",lastEventUID,pageIndex,pageSize,incidentType];
    
    NSLog(@"%@",valueStr);
    return valueStr;
}

//施工事件
- (void) constructEventBtnClick:(UIButton *)btn {
    [SVProgressHUD showWithStatus:@"正在加载中..."];
     [_searchBar resignFirstResponder];
    self.howToSearch = 3;
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_incidentEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:@"" pageIndex:@"1" pageSize:@"10" incidentType:@"3"];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEventByType";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        [SVProgressHUD dismiss];
        [_searchDataArray removeAllObjects];
        if ([requestOutginseng.Code isEqualToString:@"001"] ) {
            [_constructEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

            [_incidentEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

            [self.view addSubview:_tableView];
            _searchDataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            _tableView.hidden = NO;
            [_tableView reloadData];
        }
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

//事故事件
- (void) incidentEventBtnClick:(UIButton *)btn {
    [SVProgressHUD showWithStatus:@"正在加载中..."];
     [_searchBar resignFirstResponder];
    self.howToSearch = 4;
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_constructEventBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:@"" pageIndex:@"0" pageSize:@"10" incidentType:@"6"];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEventByType";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        [SVProgressHUD dismiss];
        [_searchDataArray removeAllObjects];
        if ([requestOutginseng.Code isEqualToString:@"001"] ) {
            [self.view addSubview:_tableView];
            _searchDataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            _tableView.hidden = NO;
            [_tableView reloadData];
        }
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

- (void)configTableView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 108, self.view.bounds.size.width, self.view.bounds.size.height - 64)];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    _tableView.hidden     = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.tableView registerNib:[UINib nibWithNibName:@"EventBaseCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_footer        = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(howSearchMoreData)];
}
- (void)configCalendarBtn {
    _calendarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _calendarBtn.backgroundColor    = [UIColor lightGrayColor];
    [_calendarBtn setBackgroundImage:[UIImage imageNamed:@"btn_calendar"] forState:UIControlStateNormal];
    _calendarBtn.frame              = CGRectMake(self.view.bounds.size.width / 2 - 30, 118, 60, 60);
    _calendarBtn.layer.cornerRadius = 29;
    _calendarBtn.backgroundColor    = [UIColor whiteColor];
    _calendarBtn.clipsToBounds      = YES;
    [_calendarBtn addTarget:self action:@selector(calendarBtnClick)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_calendarBtn];
}

- (void) calendarBtnClick {
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    calendarController.delegate   = self;
    [self presentViewController:calendarController animated:YES completion:nil];
}
#pragma mark - 日历控件的代理
-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    [_searchBar resignFirstResponder];
    self.howToSearch     = 2;
    self.currentSearchWay = 2;
    NSString *contentStr  = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    self.currentPageIndex = 1;
    self.searchContentStr = contentStr;
    [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:2 searchContentString:contentStr];
}

#pragma mark - 请求
-(NSString *)DataValueStr:(NSString *)lastEventUID pageIndex:(NSString *)pageIndex pageSize:(NSString *)pageSize eventClass:(NSString *)eventClass searchWay:(NSString *)searchWay searchContent:(NSString *)searchContent {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"Key\":\"LastEventUID\",\"Value\":\"%@\"},{\"Key\":\"PageIndex\",\"Value\":\"%@\"},{\"Key\":\"PageSize\",\"Value\":\"%@\"},{\"Key\":\"EventClass\",\"Value\":\"%@\"},{\"Key\":\"SearchWay\",\"Value\":\"%@\"},{\"Key\":\"SearchContent\",\"Value\":\"%@\"}]",lastEventUID,pageIndex,pageSize,eventClass,searchWay,searchContent];
    NSLog(@"%@",valueStr);
    return valueStr;
}
//_DataValue	__NSCFString *	@"[{\"Key\":\"LastEventUID\",\"Value\":\"\"},{\"Key\":\"PageIndex\",\"Value\":\"1\"},{\"Key\":\"PageSize\",\"Value\":\"10\"},{\"Key\":\"EventClass\",\"Value\":\"1\"},{\"Key\":\"SearchWay\",\"Value\":\"2\"},{\"Key\":\"SearchContent\",\"Value\":\"2017-03-18\"}]"	0x00006100001dd3d0
- (void)searchDataFromServer:(NSString *)lastUID  pageIndex:(NSInteger)pIndex pageSize:(NSInteger)pSize eventClass:(NSString *)eClass searchWay:(NSUInteger )sWay searchContentString:(NSString *) contetentStr{
    
    [_searchBar resignFirstResponder];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:lastUID pageIndex:[NSString stringWithFormat:@"%ld",(long)pIndex] pageSize:[NSString stringWithFormat:@"%ld",(long)pSize] eventClass:eClass searchWay:[NSString stringWithFormat:@"%ld",(unsigned long)sWay] searchContent:contetentStr];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEvent";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            _searchDataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            if (_searchDataArray.count > 0) {
                self.calendarBtn.hidden = YES;
                self.tableView.hidden   = NO;
                [self.tableView reloadData];
            }
            
        }
        [self.tableView.mj_footer endRefreshing];
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

- (void) howSearchMoreData {
    if (self.howToSearch == 1|| self.howToSearch == 2) {
        [self commonSearch];
    }
    if (self.howToSearch == 3) {
        [self searchMoreConstructBtnEvent:@"3"];
    }
    if (self.howToSearch == 4) {
        [self searchMoreConstructBtnEvent:@"6"];

    }
}

- (void) searchMoreConstructBtnEvent:(NSString *)tStr {
    self.currentPageIndex += 1;
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:@"" pageIndex:[NSString stringWithFormat:@"%ld",(long)self.currentPageIndex] pageSize:@"10" incidentType:tStr];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEventByType";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        if ([requestOutginseng.Code isEqualToString:@"001"] ) {
            [self.view addSubview:_tableView];
            NSArray *array = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            [self.searchDataArray addObjectsFromArray:array];
            [_tableView reloadData];
            
        }else {
            self.currentPageIndex -= 1;
        }
        [self.tableView.mj_footer endRefreshing];
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}

- (void) commonSearch {
    self.currentPageIndex += 1;
    CurrentEvent *model = [self.searchDataArray lastObject];
    
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:model.IncidentUID pageIndex:[NSString stringWithFormat:@"%ld",(long)self.currentPageIndex] pageSize:@"10" eventClass:self.EventType searchWay:[NSString stringWithFormat:@"%ld",(unsigned long)self.currentSearchWay] searchContent:self.searchContentStr];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEvent";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            NSArray *array = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            [self.searchDataArray addObjectsFromArray:array];
            self.calendarBtn.hidden = YES;
            [self.tableView reloadData];
        }else {
            self.currentPageIndex -= 1;
        }
        
        [self.tableView.mj_footer endRefreshing];
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}


- (void) confirmSearch {
    if (self.searchBar.text.length >1) {
        self.howToSearch      = 1;
        self.searchContentStr = self.searchBar.text;
        self.currentSearchWay = 1;
        self.currentPageIndex = 1;
        [self searchDataFromServer:@"" pageIndex:1 pageSize:10 eventClass:_EventType searchWay:1 searchContentString:self.searchBar.text];
    }
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (_titleType == 0 || _titleType== 1 || _titleType == 3){ // 当前事件 历史事件 施工事件
        
        cell.backgroundColor = kViewBackGroundColor;
        CurrentEvent *model = self.searchDataArray[indexPath.row];
        
        if (_titleType == 3){
            cell.markInt = EventListTitleTypeConstruct;
        }
        if (_titleType == 1) {
            cell.markInt = EventListTitleTypeHistory;
        }
        if (_titleType == 0) {
            cell.markInt = EventListTitleTypeCurrent;
        }
        cell.ceModel = model;
    }
    if (_titleType == 2) {  //收费事件
        TollEvent *model = self.searchDataArray[indexPath.row];
        cell.tollData = model;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_titleType == 0 || _titleType == 3) {
        CurrentEvent *model = [_searchDataArray objectAtIndex:indexPath.row];
        CGFloat cellH;
        CGFloat height;
        if ((model.DealDetail)) {
            NSString *tempStr = model.DealDetail;
            
            cellH = [self caculateCellHeight:tempStr];
            int colun = cellH / 16; // 校准
            if (colun == 1) {
                height = 110;
            }else {
                height = cellH + 16 + 44 + 5 + 20 + 8 + colun * 0.293;
            }
            
        }else {
            height = 110;
        }
        return height;
        
    }else if (_titleType == 1) {
        CurrentEvent *model = [_searchDataArray objectAtIndex:indexPath.row];
        CGFloat cellH;
        CGFloat height;
        if ((model.Content)) {
            NSString *tempStr = model.Content;
            
            cellH = [self caculateCellHeight:tempStr];
            int colun = cellH / 16; // 校准
            if (colun == 1) {
                height = 110;
            }else {
                height = cellH + 16 + 44 + 5 + 20 + 8 + colun * 0.293;
            }
            
        }else {
            height = 110;
        }
        return height;
        
    }
    else {
        return 110;
    }
}

#pragma mark - 计算cell的高度
- (CGFloat) caculateCellHeight:(NSString *)string  {
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize maxSize   = CGSizeMake([UIScreen mainScreen].bounds.size.width - 68, MAXFLOAT);
    CGFloat dealHeight = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.height;
    return dealHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CurrentEvent *model = _searchDataArray[indexPath.row];
    if ([model.IncidentParentType integerValue] == 3) {  //施工事件
        HistoryConstructDetailController *vc = [[HistoryConstructDetailController alloc] init];
        vc.CEModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    } else {  //事故事件
        HistoryInidentDetailController *vc = [[HistoryInidentDetailController alloc] init];
        vc.CEModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}



@end
